
package devbureau.fstore.common.db;

import devbureau.fstore.common.OrderLine;
import java.sql.Connection;
import java.sql.SQLException;
import org.apache.log4j.Logger;


public class CreateOrderLineDBTask extends  DBTask{

  	private static Logger logger = Logger.getLogger(CreateOrderLineDBTask.class);

	public static final String NEXT_ORDER_LINE = "values nextval for STORE.ORDER_LINE_SEQ";
    public static final String INSERT_ORDER_LINE = "insert into STORE.ORDER_LINE(ID,ORDER_ID,ITEM_ID,QUANTITY,PRICE_RUR) values (?,?,?,?,?)";
    public static final String UPDATE_ITEM_BALANCE = "update STORE.ITEM set BALANCE = (BALANCE - ?), MODIFIED = CURRENT_TIMESTAMP where ID = ?";

    private Integer orderId = null;
    private OrderLine line = null;
    private Integer lineId = null;

    public CreateOrderLineDBTask(Connection connection,Integer orderId,OrderLine line) {
        super(connection);
        this.orderId = orderId;
        this.line = line;

    }

    public void run() throws Exception {
        logger.debug("#run enter");
		try{
			connection.setAutoCommit(false);
            CreateOrderLineAction action = new CreateOrderLineAction();
            action.execute(connection, orderId, line);
            lineId = action.getLineId();
			connection.commit();
		}catch(SQLException ex){
            logger.error("SQLException", ex);
			connection.rollback();
            throw new Exception("Не удалось добавить позицию в заказ. Ошибка : " + ex.getMessage());
		}finally{
			connection.setAutoCommit(true);
		}
        logger.debug("#run exit");
    }

    public Integer getLineId(){
        return lineId;
    }
}
